// 云函数入口文件
// 点餐任务队列
const cloud = require('wx-server-sdk')

cloud.init()

const db = cloud.database()


// 创建
async function createSelect (event) {
  // 创建新记录
  await db.collection('countData').add({
    data: {
      type: event.type,
      '_openid': cloud.getWXContext().OPENID,
      nickName: event.nickName,
      avatarUrl: event.avatarUrl,
      date: new Date(),
      updateDate: new Date()
    }
  })
}

// 更新
async function updateSelect (event) {
  return db.collection('countData')
    .where({ '_openid': cloud.getWXContext().OPENID })
    .update({
      data: {
        type: event.type,
        updateDate: new Date()
      },
    })
}

// 获取单个的
async function getSelectById (event) {
  console.log(cloud.getWXContext().OPENID)
  return db.collection('countData')
    .where({ '_openid': cloud.getWXContext().OPENID })
    .get()
}


// 获取所有的
async function getSelect (event) {
  return db.collection('countData')
    .limit(100)
    .get()
}


// 云函数入口函数
exports.main = async (event, context) => {
  switch (event.action) {
    case 'create': {
      return createSelect(event)
    }
    case 'update': {
      return updateSelect(event)
    }
    case 'getById': {
      return getSelectById(event)
    }
    case 'get': {
      return getSelect(event)
    }
    default: {
      return
    }
  }
}
